<template>
  <div class="experiment-container">
    <div class="header">
      <h2 class="title">我的实验记录</h2>
      <el-button 
        type="primary" 
        @click="fetchRecords"
        :loading="loading"
        class="refresh-btn"
      >
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>
    
    <el-card shadow="hover" class="table-card">
      <el-table 
        :data="experimentList" 
        style="width: 100%"
        v-loading="loading"
        :default-sort="{ prop: 'completed_at', order: 'descending' }"
        stripe
        border
      >
        <el-table-column 
          prop="experiment_name" 
          label="实验名称" 
          width="150"
          sortable
        />
        <el-table-column prop="status" label="状态" width="150">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)"
              effect="light"
              round
            >
              {{ row.status || '未开始' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="student_name" 
          label="学生姓名" 
          width="180"
        />
        <el-table-column 
          prop="completed_at" 
          label="完成时间"
          sortable
          width="200"
        >
          <template #default="{ row }">
            <span :class="{ 'uncompleted': !row.completed_at }">
              {{ formatDate(row.completed_at) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分" width="120" align="center">
          <template #default="{ row }">
            <el-tag 
              v-if="row.score !== null && row.score !== undefined"
              :type="getScoreType(row.score)"
            >
              {{ row.score }}
            </el-tag>
            <span v-else class="no-score">--</span>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination" v-if="experimentList.length > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalRecords"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

// 响应式数据
const experimentList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const totalRecords = ref(0)
const pageSize = ref(10)

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '未完成'
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString().slice(0, 5)
}

// 状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '已完成': 'success',
    '进行中': 'primary',
    '未开始': 'info',
    '已过期': 'danger'
  }
  return statusMap[status] || 'info'
}

// 分数标签类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 60) return 'warning'
  return 'danger'
}

// 获取实验记录的函数
const fetchRecords = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/student-answers/', {
      params: {
        page: currentPage.value,
        page_size: pageSize.value
      }
    })
    experimentList.value = response.data.results || response.data
    totalRecords.value = response.data.count || experimentList.value.length
  } catch (error) {
    console.error('获取实验记录失败:', error)
    ElMessage.error('获取实验记录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchRecords()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.experiment-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.table-card {
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.uncompleted {
  color: #999;
  font-style: italic;
}

.no-score {
  color: #ccc;
}

.refresh-btn {
  margin-left: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .refresh-btn {
    margin-top: 10px;
    margin-left: 0;
  }
  
  /* 在小屏幕下调整表格列宽 */
  :deep(.el-table td),
  :deep(.el-table th) {
    padding: 8px 0;
  }
}
</style>